﻿using System;
using System.IO;
using System.Text;

using Utilities.IO;

namespace Utilities.Media.Containers
{
    public class RiffContainer : StreamContainer
    {
        public int DataSize { get; protected set; }
        public string Format { get; protected set; }

        // Lecture
        public RiffContainer(string path) : this(File.Open(path, FileMode.Open))
        {
        }
        public RiffContainer(Stream stream) : base(stream)
        {
        }

        // Ecriture
        public RiffContainer(string path, string format) : this(File.Open(path, FileMode.Create))
        {
        }
        public RiffContainer(Stream stream, string format) : base(stream)
        {
            Format = format;
            if (format.Length != 4)
                throw new FormatException();
        }

        // TODO: Détailler les exceptions
        public virtual void ReadHeader()
        {
            DataStream dataStream = new DataStream(BaseStream, Encoding.ASCII, StringType.None);

            string chunkID = dataStream.ReadString(4);
            if (chunkID != "RIFF")
                throw new InvalidDataException();

            DataSize = dataStream.ReadInt32();
            Format = dataStream.ReadString(4);
        }
        public virtual void WriteHeader()
        {
            DataStream dataStream = new DataStream(BaseStream, Encoding.ASCII, StringType.None);
            dataStream.Write("RIFF");
            dataStream.Write(Int32.MaxValue);
            dataStream.Write(Format);
        }
    }
}
